<template>
  <!-- sync 给子传值 并且子组件要修改数据 和v-module 一样但是可以使用多次 -->
  <el-dialog
    :title="titleText"
    :visible="showDialog"
    width="50%"
    @close="onClose"
  >
    <el-form
      ref="addForm"
      :rules="addFormRules"
      :model="form"
      label-width="100px"
    >
      <el-form-item prop="name" label="部门名称">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item prop="code" label="部门编码">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item prop="manager" label="部门负责人">
        <el-select
          v-model="form.manager"
          :loading="isLoading"
          loading-text="加载中..."
          placeholder="请选择负责人"
          @focus="loadEmpList"
        >
          <el-option
            v-for="item in employeesList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="introduce" label="部门介绍">
        <el-input v-model="form.introduce" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" :loading="btnLoading" @click="onSave">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getEmployeesSimpleList } from '@/api/employees'
import {
  getDepartments,
  addDepartment,
  updateDepartments
} from '@/api/departments'
export default {
  props: {
    showDialog: {
      type: Boolean,
      required: true
    },
    row: {
      type: Object,
      required: true
    }
  },
  data() {
    // 判断部门是否存在
    const checkDeptNameIsRepeat = async(rule, value, callback) => {
      let isRepeat
      if (this.form.id) {
        // 编辑
        const { depts } = await getDepartments()
        const slibings = depts.filter(
          item => item.id !== this.row.id && item.pid === this.row.pid
        )
        isRepeat = slibings.some(item => item.name === value)
      } else {
        // 添加
        if (!this.row.children) return callback()
        isRepeat = this.row.children.some(item => item.name === value)
      }
      return isRepeat ? callback(new Error('部门存在')) : callback()
    }
    const checkDeptCodeIsRepeat = async(rule, value, callback) => {
      const res = await getDepartments()
      let isRepeat
      if (this.form.id) {
        // 编辑
        isRepeat = res.depts.some(
          item => item.id !== this.row.id && item.code === value
        )
      } else {
        // 添加
        isRepeat = res.depts.some(item => item.code === value)
      }
      return isRepeat ? callback(new Error('编码存在')) : callback()
    }
    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      employeesList: [],
      isLoading: false,
      addFormRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 2,
            max: 50,
            message: '部门名称要求2-50个字符',
            trigger: 'blur'
          },
          { validator: checkDeptNameIsRepeat, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 2,
            max: 50,
            message: '部门编码要求2-50个字符',
            trigger: 'blur'
          },
          { validator: checkDeptCodeIsRepeat, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            min: 2,
            max: 300,
            message: '部门介绍要求2-50个字符'
          }
        ]
      },
      btnLoading: false
    }
  },
  computed: {
    titleText() {
      return (this.form.id ? '查看' : '添加') + '部门'
    }
  },

  created() {},
  // 定义方法
  methods: {
    onClose() {
      this.$refs.addForm.resetFields()
      this.$emit('update:show-dialog', false)
      setTimeout(() => {
        this.form = {
          name: '',
          code: '',
          manager: '',
          introduce: ''
        }
      }, 200)
    },
    async loadEmpList() {
      this.isLoading = true
      const res = await getEmployeesSimpleList()
      this.employeesList = res
      this.isLoading = false
    },
    async onSave() {
      try {
        this.btnLoading = true
        await this.$refs.addForm.validate()
        if (this.form.id) {
          // 修改
          const { code, name, id, introduce, manager } = this.form
          await updateDepartments({ code, name, id, introduce, manager })
        } else {
          // 添加
          this.form.pid = this.row.id || ''
          await addDepartment(this.form)
        }
        this.btnLoading = false
        this.onClose()
        this.$emit('addSuccess')
        this.$message.success('成功！')
      } catch (err) {
        this.btnLoading = false
        this.$message.error('不可以这样~')
      }
    },
    serForm() {
      this.form = JSON.parse(JSON.stringify(this.row))
    }
  }
}
</script>

<style scoped lang="scss">
.el-select {
  width: 100%;
}
</style>
